#source url from wiki:  http://en.wikipedia.org/wiki/List_of_countries_and_territories_by_continent
$input =  "territories.wiki";
$output = "territories.tbox";
$rolelocated = "locatedIn";
$rolehascap = "hasCapital";
$cplocation = "Location";

open (CT, "< $input") || die "Cannot open the countries file.\n";
open (OUT, "> $output") || die "Cannot create output!\n";
# get each line
@lines = <CT>;
$conti = "";
$ctr = "";
$cap = "";
$find = 0;
$count = 4; # four lines for each country
foreach $line (@lines){
	if($line =~ /[=]{3}(.+)[=]{3}/){
		$conti = $1;
		next;		
	}
	if($line =~ /^\s+$/ || $line !~ /^[|].+$/){
		next;
	}
	if($find){	
		if($count == 3){
			if($line =~ /[|]\s+[']{1,}\[{2}(.+)\]\][']{1,}.+/){
				$ctr = $1 ;
			}else{
				print "Error in parsing the country name: $line\n";
			}
		}elsif($count == 2){
			if($line =~ /^[|]\s+\[\[(.+?)\]\].*$/){
				$cap = $1;
			}else{
				# print "Error in parsing the capital name: $line\n";
				# this country/terro does not have one!
				$cap = "N/A";
			}
		}
		$count--;
		if($count == 0 ){
			$find = 0;
			#replace all spaces
			$ctr =~ s/\s+/_/g;
			$cap =~ s/\s+/_/g;
			$conti =~ s/\s+/_/g;
			print OUT "(implies $ctr (forall (role $rolelocated) $conti) )  \n";
			print OUT "(implies $ctr $cplocation)\n";
			print OUT "(implies $conti $cplocation)\n";
			if($cap ne "N/A"){
				print OUT "(implies $ctr (forall (role $rolehascap) $cap) )  \n";
				print OUT "(implies $cap (forall (role $rolelocated) $ctr) )  \n";
				print OUT "(implies $cap $cplocation)\n";
			}

		}
	}
	if($line =~ /^[|][-]$/){
		$find = 1;
		$count = 4;
	}

	
}